package com.app.service.impl;

import com.app.common.SystemConstant;
import com.app.mapper.UserMapper;
import com.app.model.UserModel;
import com.app.service.LogonService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class LogonServiceImpl implements LogonService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Result logon(String mobile, String code) {

        String sql = "SELECT * FROM tb_msg_identifiy WHERE mi_mobile='" + mobile + "' AND mi_idenCode = '" + code + "'";
        List<Map<String, Object>> identifiylist_maps = jdbcTemplate.queryForList(sql);
        if (identifiylist_maps == null && identifiylist_maps.size() == 0) {
            return Result.success(405);
        }
        UserModel userModel = new UserModel();
        userModel.setMobile(mobile);
        userModel.setUserName(mobile);
        userModel.setCrtTime(CommonHelp.getNowTimestamp().toString());
        userModel.setCRegisterState(0);
        userModel.setFaceUrl(SystemConstant.DEFAULT_FACE_URL);
        userMapper.insert(userModel);
        return Result.success(userModel);
    }

    public Result<String> updateUserAvatar(HttpSession session, MultipartFile file){

        //第一步：写一个路径，和配置类一样
        String realPath = session.getServletContext().getRealPath("/upload");
        //第二步：用文件检测目录，没有就创建
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //第三步：统一后缀名
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String png = originalFilename.substring(i);
        String filename = UUID.randomUUID().toString().toUpperCase() + png;
        //第四步：在该目录下创建一个空白文件，文件名字随意
        File dest = new File(dir, filename); //在这个目录下创建一个空白的文件
        //第五步：把形参的文件数据用提供的api写入到空白文件中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //第六步：：拼接完整地址 目录加文件名字
        String avatar = "/test/" + filename;
        return Result.success(avatar);
    }
}
